html
预览
{{define "records"}}
<div class="records-container">
    <h2>我的短链记录</h2>

    <!-- 表格、空状态、加载状态结构不变 -->
    <table class="records-table" id="recordsTable">
        <thead>
        <tr>
            <th>ID</th>
            <th>长链接</th>
            <th>短链接</th>
            <th>创建时间</th>
        </tr>
        </thead>
        <tbody id="recordsBody"></tbody>
    </table>
    <p class="empty" id="emptyState" style="display: none;">暂无短链记录，<a href="/url/createPage">去生成一个</a></p>
    <div class="loading" id="loadingState" style="display: none; text-align: center; padding: 20px;">加载中...</div>

    <!-- 分页控件结构不变 -->
    <div class="pagination">
        <div class="page-size-selector">
            <label>每页显示：</label>
            <select name="pageSize" id="pageSizeSelect" onchange="changePageSize(this.value)">
                <option value="5" {{if eq .PageSize 5}}selected{{end}}>5条</option>
                <option value="10" {{if eq .PageSize 10}}selected{{end}}>10条</option>
                <option value="20" {{if eq .PageSize 20}}selected{{end}}>20条</option>
                <option value="50" {{if eq .PageSize 50}}selected{{end}}>50条</option>
            </select>
        </div>
        <div class="pagination-info" id="paginationInfo">
            <p>共 {{.Total}} 条记录，{{.TotalPages}} 页，当前第 {{.Page}} 页</p>
        </div>
        <div class="pagination-buttons" id="paginationButtons"></div>
    </div>
</div>

<script>
    let currentPage = {{.Page}};
    let currentPageSize = {{.PageSize}};
    let totalRecords = {{.Total}};
    let totalPages = {{.TotalPages}};

    // 核心：从模板变量 .User.Username 获取当前登录用户的用户名（即 creator）
    // 模板渲染时已传递 User 变量，直接在 JS 中通过 {{.User.Username}} 注入
    const currentCreator = "{{.User.Username}}";

    // 构造查询参数（包含 creator 和 source）
    const fixedQueryParams = {
        source: "SELF",                // 固定 source 为 SELF
        creator: currentCreator        // 从模板获取的 creator
    };

    // 页面加载完成后初始化数据
    document.addEventListener('DOMContentLoaded', function() {
        loadRecords(currentPage, currentPageSize);
    });

    // 加载短链记录（POST 请求，携带 creator 参数）
    function loadRecords(page, pageSize) {
        document.getElementById('loadingState').style.display = 'block';
        document.getElementById('recordsTable').style.display = 'none';
        document.getElementById('emptyState').style.display = 'none';

        // 构造完整请求参数（符合 UrlMapPageMapRequest 结构体）
        const requestData = {
            ...fixedQueryParams,  // 合并 creator、source
            pageNum: page,        // 分页参数：当前页码
            pageSize: pageSize    // 分页参数：每页条数
        };

        // 发起 POST 请求
        fetch("/url/pageQuery", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)  // 传递包含 creator 的参数
        })
            .then(response => response.json())
            .then(result => {
                document.getElementById('loadingState').style.display = 'none';

                if (result.code === '00000' && result.data) {
                    totalRecords = result.data.total;
                    totalPages = Math.ceil(totalRecords / pageSize);
                    currentPage = page;
                    currentPageSize = pageSize;

                    renderTable(result.data.list);
                    updatePaginationInfo();
                    renderPaginationButtons();
                } else {
                    document.getElementById('emptyState').style.display = 'block';
                }
            })
            .catch(error => {
                console.error('加载失败:', error);
                document.getElementById('loadingState').style.display = 'none';
                document.getElementById('emptyState').style.display = 'block';
            });
    }

    // 以下函数（renderTable、updatePaginationInfo 等）保持不变
    function renderTable(records) {
        const tableBody = document.getElementById('recordsBody');
        tableBody.innerHTML = '';

        if (records.length === 0) {
            document.getElementById('recordsTable').style.display = 'none';
            document.getElementById('emptyState').style.display = 'block';
            return;
        }

        document.getElementById('recordsTable').style.display = 'table';
        document.getElementById('emptyState').style.display = 'none';

        records.forEach(record => {
            const row = document.createElement('tr');
            // 注意：字段名改为小写（与后端返回一致）
            row.innerHTML = `
            <td>${record.id}</td>
            <td><a href="${record.longUrl}" target="_blank" class="long-url">${record.longUrl}</a></td>
            <td><a href="${record.shortUrl}" target="_blank" class="short-url">${record.shortUrl}</a></td>
            <td>${record.createTime}</td>
        `;
            tableBody.appendChild(row);
        });
    }

    function updatePaginationInfo() {
        const infoEl = document.getElementById('paginationInfo').querySelector('p');
        infoEl.textContent = `共 ${totalRecords} 条记录，${totalPages} 页，当前第 ${currentPage} 页`;
    }

    function renderPaginationButtons() {
        const buttonsContainer = document.getElementById('paginationButtons');
        buttonsContainer.innerHTML = '';

        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, currentPage + 2);

        if (endPage - startPage < 4 && totalPages >= 5) {
            if (startPage === 1) endPage = 5;
            else if (endPage === totalPages) startPage = totalPages - 4;
        }

        // 上一页
        const prevBtn = document.createElement('a');
        prevBtn.href = 'javascript:void(0)';
        prevBtn.className = `pagination-btn ${currentPage <= 1 ? 'disabled' : ''}`;
        prevBtn.textContent = '上一页';
        prevBtn.onclick = () => currentPage > 1 && loadRecords(currentPage - 1, currentPageSize);
        buttonsContainer.appendChild(prevBtn);

        // 首页和省略号
        if (startPage > 1) {
            buttonsContainer.appendChild(createPageButton(1));
            if (startPage > 2) {
                const ellipsis = document.createElement('span');
                ellipsis.className = 'pagination-ellipsis';
                ellipsis.textContent = '...';
                buttonsContainer.appendChild(ellipsis);
            }
        }

        // 中间页码
        for (let i = startPage; i <= endPage; i++) {
            buttonsContainer.appendChild(createPageButton(i));
        }

        // 末页和省略号
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                const ellipsis = document.createElement('span');
                ellipsis.className = 'pagination-ellipsis';
                ellipsis.textContent = '...';
                buttonsContainer.appendChild(ellipsis);
            }
            buttonsContainer.appendChild(createPageButton(totalPages));
        }

        // 下一页
        const nextBtn = document.createElement('a');
        nextBtn.href = 'javascript:void(0)';
        nextBtn.className = `pagination-btn ${currentPage >= totalPages ? 'disabled' : ''}`;
        nextBtn.textContent = '下一页';
        nextBtn.onclick = () => currentPage < totalPages && loadRecords(currentPage + 1, currentPageSize);
        buttonsContainer.appendChild(nextBtn);
    }

    function createPageButton(pageNum) {
        const btn = document.createElement('a');
        btn.href = 'javascript:void(0)';
        btn.className = `pagination-btn ${pageNum === currentPage ? 'active' : ''}`;
        btn.textContent = pageNum;
        btn.onclick = () => loadRecords(pageNum, currentPageSize);
        return btn;
    }

    function changePageSize(size) {
        currentPageSize = parseInt(size);
        loadRecords(1, currentPageSize);
        document.getElementById('pageSizeSelect').value = size;
    }
</script>
{{end}}

{{template "base.html" .}}